package mrpanyu.guitool.yunduan;

import java.awt.image.BufferedImage;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;

import mrpanyu.guitool.base.annotation.Action;
import mrpanyu.guitool.base.annotation.Parameter;
import mrpanyu.guitool.base.annotation.ToolModel;
import mrpanyu.guitool.base.model.ParameterType;
import mrpanyu.guitool.base.model.Tool;
import mrpanyu.guitool.base.util.CommonUtils;
import mrpanyu.guitool.base.util.ScreenCapture;

@ToolModel(displayName = "QR二维码解析", enableProfiles = false)
public class QRReader {

	@Parameter(displayName = "复制到剪贴板", type = ParameterType.SELECT, options = { "Y", "N" }, order = 1)
	private String copyToClipboard = "Y";

	@Action(displayName = "截屏解析", order = 1)
	public void readSnapshot(Tool tool) {
		tool.clearMessages();
		ScreenCapture.capture(img -> {
			readQRCode(tool, img);
		});
	}

	@Action(displayName = "解析剪贴板图片", order = 2)
	public void readClipboard(Tool tool) {
		tool.clearMessages();
		BufferedImage img = CommonUtils.getClipboardImage();
		if (img == null) {
			tool.errorMessage("剪贴板中无图片信息");
		} else {
			readQRCode(tool, img);
		}
	}

	private void readQRCode(Tool tool, BufferedImage img) {
		try {
			BufferedImageLuminanceSource luminateSource = new BufferedImageLuminanceSource(img);
			MultiFormatReader reader = new MultiFormatReader();
			Map<DecodeHintType, Object> hints = new HashMap<>();
			hints.put(DecodeHintType.POSSIBLE_FORMATS, EnumSet.allOf(BarcodeFormat.class));
			hints.put(DecodeHintType.TRY_HARDER, true);
			hints.put(DecodeHintType.PURE_BARCODE, true);
			hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
			reader.setHints(hints);
			String text = reader.decode(new BinaryBitmap(new HybridBinarizer(luminateSource))).getText();
			tool.infoMessage(text);
			if ("Y".equals(copyToClipboard)) {
				CommonUtils.setClipboardText(text);
			}
		} catch (Exception e) {
			e.printStackTrace();
			tool.errorMessage(e);
		}
	}

}
